package com.woyou.ui.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import retrofit.RetrofitError;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.citaq.ideliver.R;
import com.woyou.bean.CodeListResult;
import com.woyou.bean.CodeResult;
import com.woyou.bean.Info;
import com.woyou.bean.MyAddress;
import com.woyou.bean.Result;
import com.woyou.bean.UserInfo;
import com.woyou.bean.rpc.LoginReq;
import com.woyou.bean.rpc.ManagerAddrReq;
import com.woyou.bean.rpc.PhonePwdReq;
import com.woyou.bean.rpc.PhoneReq;
import com.woyou.service.LocationLoopService;
import com.woyou.service.NetWorkCenter;
import com.woyou.ui.fragment.IndexFragment_;
import com.woyou.utils.CharCheckUtil;
import com.woyou.utils.DeviceUtils;
import com.woyou.utils.Dialog;
import com.woyou.utils.eventbus.EventInfoSetup;

import de.greenrobot.event.EventBus;

/**
 * 登录LoginFragment
 * 
 * @author tanglc
 */
@EActivity(R.layout.fm_login)
public class LoginActivity extends BaseActivity {

	private int recLen = 0;
	Timer timer;

	PhoneReq phoneReq;
	@SuppressWarnings("rawtypes")
	CodeResult checkCodeResult;
	LoginReq loginReq;// 登录请求
	List<MyAddress> list = new ArrayList<MyAddress>();

	Dialog dialog = new Dialog();

	@ViewById
	RelativeLayout myback;
	@ViewById
	TextView head_title;
	@ViewById(R.id.fm_login_phoneedit)
	EditText phoneEdit;
	@ViewById(R.id.fm_login_pwdedit)
	EditText codeEdit;
	@ViewById(R.id.fm_login_codebtn)
	Button codeBtn;
	@ViewById(R.id.fm_login_loginbtn)
	Button loginBtn;
	@ViewById
	LinearLayout fm_login_agreement, hidekeyboard, isagreement, clearphone, clearpwd;
	@ViewById
	CheckBox login_checked;

	private String phone = null;
	private LocationLoopService loopService;

	@AfterViews
	public void init() {
		EventBus.getDefault().post(new EventInfoSetup());
		loopService = LocationLoopService.getInstance(mContext);
	}
	
	@Override
	public void onResume() {
		super.onResume();
		mUserModel.deleteUserDao();
		progress = getProgressDialog("正在为您发送验证码,请稍后...");
		progress.setCancelable(false);
		List<MyAddress> list = mUserModel.queryAddrList();
		if (list != null) {
			list.clear();
		}
		initView();
		cleraView();
	}
	
	public void initView() {
		head_title.setText("快捷登录");
		phoneEdit.addTextChangedListener(new PhoneEditChangedListener());
		codeEdit.addTextChangedListener(new CodeEditChangedListener());
	}

	@Click({ R.id.fm_login_codebtn, R.id.fm_login_loginbtn, R.id.login_checked, R.id.clearphone, R.id.clearpwd,
			R.id.fm_login_agreement, R.id.myback, R.id.hidekeyboard, R.id.isagreement })
	void loginOnClick(View view) {
		switch (view.getId()) {
		case R.id.fm_login_codebtn:
			// 获取手机号发送请求向手机发送验证码
			hideSoftInput(mActivity, phoneEdit);
			phone = phoneEdit.getText().toString();
			if (CharCheckUtil.isPhoneNum(phone)) {
				// 获取验证码
				if (recLen > 0 && recLen != 61 && !codeBtn.getText().toString().equals("获取验证码")) {
					dialog.Toast(mActivity, "您的验证码已发送！");
				} else {
					codeBtn.setEnabled(false);
					codeEdit.setText("");
					getCheckCode();
				}
			} else {
				dialog.Toast(mActivity, "输入的手机号码有误，请确认！");
			}
			break;

		case R.id.fm_login_loginbtn:
			// 点击按钮登录
			hideSoftInput(mActivity, phoneEdit);
			if (LoginCheck()) {
				userLogin();
			}
			break;

		case R.id.fm_login_agreement:
			// 跳转到协议界面
			openActivity(AgreementActivity_.class, null);
			break;

		case R.id.myback:
			backOperate();
			break;

		case R.id.login_checked:
		case R.id.isagreement:
			// 勾选登录的服务协议
			hideSoftInput(mActivity, phoneEdit);
			if (login_checked.isChecked()) {
				login_checked.setChecked(false);
				login_checked.setBackgroundResource(R.raw.checkbox1);
				loginBtn.setBackgroundResource(R.drawable.login_bg);
				loginBtn.setEnabled(false);
			} else {
				login_checked.setChecked(true);
				login_checked.setBackgroundResource(R.raw.checkbox2);
				if (phoneEdit.getText().toString().length() == 11
						&& CharCheckUtil.isPhoneNum(phoneEdit.getText().toString())
						&& codeEdit.getText().toString().length() == 3) {
					loginBtn.setBackgroundResource(R.drawable.login_bgdown);
					loginBtn.setEnabled(true);
				}
			}
			break;

		case R.id.clearphone:
			// 清空手机号
			phoneEdit.setText("");
			clearphone.setVisibility(View.GONE);
			break;

		case R.id.clearpwd:
			// 清空验证码
			codeEdit.setText("");
			loginBtn.setBackgroundResource(R.drawable.login_bg);
			loginBtn.setEnabled(false);
			clearpwd.setVisibility(View.GONE);
			break;

		case R.id.hidekeyboard:
			// 隐藏键盘
			hideSoftInput(mActivity, phoneEdit);
			dismissProgressDialog();
			break;
		}
	}

	/**
	 * 获取验证码 tanglc
	 */
	@Background
	void getCheckCode() {
		if (!NetWorkCenter.isNetworkConnected(mActivity)) {
			showToast("网络根本没连,赶紧检查");
			codeBtn.setEnabled(true);
			return;
		}
		showProgressDialog();
		try {
			// 设置请求参数
			phoneReq = new PhoneReq();
			phoneReq.setPhone(phoneEdit.getText().toString());
			checkCodeResult = mUserModel.getCheckCode(phoneReq); // 向服务器请求并获得数据
			// 解析服务器返回的数据
			getCheckCodeResult();
		} catch (RetrofitError e) {
			codeBtn.setEnabled(true);
			dismissProgressDialog();
			switch (e.getKind()) {
			case HTTP:
				showToast("很遗憾，网络不给力！");
				return;
			case CONVERSION:
				showToast("很抱歉，服务器又任性了！");
				return;
			case NETWORK:
				showToast("很遗憾，网络不给力！");
				return;
			case UNEXPECTED:
				showToast("很抱歉，服务器又任性了！");
				return;
			}
		}
	}

	/**
	 * 解析服务器返回的数据 tanglc 上午10:35:01
	 */
	@UiThread
	void getCheckCodeResult() {
		if (checkCodeResult.code == 1) {
			recLen = 61;
			Message message = handler.obtainMessage(1);
			handler.sendMessageDelayed(message, 1000);
			dismissProgressDialog();
			showToast(checkCodeResult.msg);
			getCodeSuccess();
		} else {
			codeBtn.setEnabled(true);
			dismissProgressDialog();
			dialog.Toast(mActivity, checkCodeResult.msg);
		}
	}

	boolean isSleep = true;
	// 设置获取验证码按钮倒计时
	@SuppressLint("HandlerLeak")
	final Handler handler = new Handler() {
		public void handleMessage(Message msg) { // handle message
			switch (msg.what) {
			case 1:
				recLen--;
				codeBtn.setText("重新获取" + recLen + "s");
				codeBtn.setBackgroundResource(R.drawable.login_bg);
				codeBtn.setEnabled(true);
				if (recLen > 0) {
					isSleep = false;
					Message message = handler.obtainMessage(1);
					handler.sendMessageDelayed(message, 1000); // send message
				} else {
					recLen = 61;
					isSleep = true;
					codeBtn.setText("获取验证码");
					if (CharCheckUtil.isPhoneNum(phoneEdit.getText().toString())) {
						codeBtn.setBackgroundResource(R.drawable.login_bgdown);
					}
				}
			}
			super.handleMessage(msg);
		}
	};

	/**
	 * 点击登录按钮，请求接口数据
	 * 
	 * tanglc
	 */
	@Background
	void userLogin() {
		if (!NetWorkCenter.isNetworkConnected(mActivity)) {
			showToast("网络根本没连,赶紧检查");
			return;
		}
		showProgressDialog();
		try {
			// 设置请求参数
			loginReq = new LoginReq();
			loginReq.setPhone(phoneEdit.getText().toString());
			String pwd = codeEdit.getText().toString() + producePwd();
			loginReq.setPwd(pwd);
			String pushToken = DeviceUtils.getPushToken(mContext.getApplicationContext());
			loginReq.setToken(pushToken);
			loginReq.setvCode(codeEdit.getText().toString());
			CodeResult<UserInfo> loginResult = mUserModel.userLogin(loginReq); // 向服务器请求并获得数据
			dismissProgressDialog();
			// 登录接口返回数据解析
			userLoginResult(loginResult);
			hideSoftInput(mActivity, codeEdit);
		} catch (RetrofitError e) {
			dismissProgressDialog();
			switch (e.getKind()) {
			case HTTP:
				showToast("很遗憾，网路不给力！");
				return;
			case CONVERSION:
				showToast("很抱歉，服务器又任性了！");
				return;
			case NETWORK:
				showToast("很遗憾，网路不给力！");
				return;
			case UNEXPECTED:
				showToast("很抱歉，服务器又任性了！");
				return;
			}
		}
	}

	// 设置密码
	public String producePwd() {
		Random random = new Random();
		int num = 0;
		while (true) {
			num = (int) (random.nextDouble() * (10000000 - 1000000) + 1000000);
			if (!(num + "").contains("4"))
				break;
		}
		return String.valueOf(num);
		// 为了兼容1.9 密码规则为 验证码后加7个0
		// return "0000000";
	}

	/**
	 * 登录成功，对接口返回的数据进行解析
	 * 
	 * tanglc 上午10:36:28
	 * 
	 * @param loginResult
	 */
	@UiThread
	void userLoginResult(final CodeResult<UserInfo> loginResult) {
		if (loginResult.code == 1 || loginResult.code == 0) { // 返回结果（0：用户第一次登录(注册)；1：登录成功；-1：验证码错误；-2：未知错误）
			if (mUserModel.queryAddrList() != null && mUserModel.queryAddrList().size() > 0) {
				list.addAll(mUserModel.queryAddrList());
			}
			mShopsModel.clearKeys();
			mUserModel.clearAdreessKeys();
			queryUserInfo(); // 获取用户信息
		} else {
			runOnUI(new Runnable() {
				@Override
				public void run() {
					codeEdit.setText("");
					loginBtn.setBackgroundResource(R.drawable.login_bg);
					loginBtn.setEnabled(false);
					dialog.Toast(mActivity, loginResult.msg);
				}
			});
		}
	}

	/**
	 * 获取用户信息 tanglc 上午10:20:36
	 */
	@Background
	void queryUserInfo() {
		try {
			// 设置接口请求参数
			PhonePwdReq phonePwdReq = new PhonePwdReq();// 接口请求参数
			if (loopService.getChosenAddr() != null) {
				phonePwdReq.setLat(loopService.getChosenAddr().getLat());
				phonePwdReq.setLng(loopService.getChosenAddr().getLng());
			} else {
				if (mBaiduLocationService.getLastLocation() != null) {
					phonePwdReq.setLat(mBaiduLocationService.getLastLocation().getLatitude() + "");
					phonePwdReq.setLng(mBaiduLocationService.getLastLocation().getLongitude() + "");
				} else {
					phonePwdReq.setLat("");
					phonePwdReq.setLng("");
				}
			}
			UserInfo userInfo = mUserModel.getUserInfo();
			phonePwdReq.setuId(userInfo.getuId());
			phonePwdReq.setPwd(userInfo.getPwd());
			final Result<UserInfo> result = mUserModel.v2_1queryUserInfo(phonePwdReq); // 与服务器交互获取数据
			runOnUI(new Runnable() {
				
				@Override
				public void run() {
					// 解析服务器返回的数据
					getUserInfoResult(result);
				}
			});
		} catch (RetrofitError e) {
			switch (e.getKind()) {
			case HTTP:
				return;
			case CONVERSION:
				return;
			case NETWORK:
				return;
			case UNEXPECTED:
				return;
			}
		}
	}

	private void getUserInfoResult(Result<UserInfo> result) {
		if (result != null && result.code == 1) {
			EventBus.getDefault().post(new EventInfoSetup());
			if (list != null && list.size() > 0) {
				// 更新缓存地址
				for (int i = 0; i < result.getData().getAddrList().size(); i++) {
					list.add(result.getData().getAddrList().get(i));
				}
				managerAddr(list);
			} else {
				hideSoftInput(mActivity, codeEdit);
				finish();
				phoneEdit.setText("");
				codeEdit.setText("");
				showToast("登录成功");
			}
		} else {
			showToast(result.msg);
		}
	}

	/**
	 * 成功获取密码后，让密码框获取焦点，并弹出软件盘
	 */
	InputMethodManager imm = null;

	public void getCodeSuccess() {
		codeEdit.setFocusable(true);
		codeEdit.setFocusableInTouchMode(true);
		codeEdit.requestFocus();
		imm = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(codeEdit, 0);
	}

	/**
	 * 登录后校验地址，更新最新地址
	 */
	@Background
	void managerAddr(List<MyAddress> list) {
		ManagerAddrReq managerAddrReq = new ManagerAddrReq();
		managerAddrReq.setUid(mUserModel.getUserInfo().getuId());
		managerAddrReq.setPwd(mUserModel.getUserInfo().getPwd());
		managerAddrReq.setList(list);
		mUserModel.managerAddr(managerAddrReq);
		try {
			CodeListResult<MyAddress> result = mUserModel.managerAddr(managerAddrReq);
			if (result != null && result.code == 1) {
				hideSoftInput(mActivity, codeEdit);
				finish();
				phoneEdit.setText("");
				codeEdit.setText("");
				showToast("登录成功");
			} else {
				hideSoftInput(mActivity, codeEdit);
				finish();
				showToast(result.msg);
			}
		} catch (RetrofitError e) {
			switch (e.getKind()) {
			case HTTP:
				return;
			case CONVERSION:
				return;
			case NETWORK:
				return;
			case UNEXPECTED:
				return;
			}
		}
	}

	/**清空*/
	public void cleraView() {
		phoneEdit.setText("");
		codeEdit.setText("");
		login_checked.setChecked(true);
		login_checked.setBackgroundResource(R.raw.checkbox2);
		
		codeBtn.setBackgroundResource(R.drawable.login_bg);
		codeBtn.setEnabled(false);
		loginBtn.setBackgroundResource(R.drawable.login_bg);
		loginBtn.setEnabled(false);
	}

	/**
	 * 登录参数校验
	 * 
	 * tanglc
	 * 
	 * @param phone
	 * @param pwd
	 * @return false || true
	 */
	public boolean LoginCheck() {
		if (!CharCheckUtil.isPhoneNum(phoneEdit.getText().toString())) {
			dialog.Toast(mActivity, "您输入的手机号码有误，请重新输入！");
			return false;
		}
		if (!CharCheckUtil.isAllDigit(codeEdit.getText().toString())) {
			dialog.Toast(mActivity, "您输入的验证码有误，请重新输入！");
			return false;
		}
		return true;
	}

	/**
	 * 手机号监听
	 * 
	 * @author shenzhou 2015年1月9日
	 */
	class PhoneEditChangedListener implements TextWatcher {
		private CharSequence temp;// 监听前的文本
		private int editStart;// 光标开始位置
		private int editEnd;// 光标结束位置
		private final int charMaxNum = 11;

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			temp = s;
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			
		}

		@Override
		public void afterTextChanged(Editable s) {
			editStart = phoneEdit.getSelectionStart();
			editEnd = phoneEdit.getSelectionEnd();
			phone = phoneEdit.getText().toString();
			if (temp.length() == charMaxNum && CharCheckUtil.isPhoneNum(phoneEdit.getText().toString())) {

				if (isSleep) {
					codeBtn.setBackgroundResource(R.drawable.login_bgdown);
					codeBtn.setEnabled(true);
				}
				if (codeEdit.getText().toString().length() == 3 && login_checked.isChecked()) {
					loginBtn.setBackgroundResource(R.drawable.login_bgdown);
					loginBtn.setEnabled(true);
				}
			} else if (temp.length() > charMaxNum) {
				s.delete(editStart - 1, editEnd);
				int tempSelection = editStart;
				phoneEdit.setText(s);
				phoneEdit.setSelection(tempSelection);
			} else {
				codeBtn.setBackgroundResource(R.drawable.login_bg);
				codeBtn.setEnabled(false);
				loginBtn.setBackgroundResource(R.drawable.login_bg);
				loginBtn.setEnabled(false);
			}
			if (phoneEdit.length() > 0) {
				clearphone.setVisibility(View.VISIBLE);
			} else {
				clearphone.setVisibility(View.GONE);
			}
		}
	}

	/**
	 * 验证码监听
	 * 
	 * @author shenzhou 2015年1月9日
	 */
	class CodeEditChangedListener implements TextWatcher {
		private CharSequence temp;// 监听前的文本
		private int editStart;// 光标开始位置
		private int editEnd;// 光标结束位置
		private final int charMaxNum = 3;

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count, int after) {
			temp = s;
		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
		}

		@Override
		public void afterTextChanged(Editable s) {
			editStart = codeEdit.getSelectionStart();
			editEnd = codeEdit.getSelectionEnd();
			phone = phoneEdit.getText().toString();
			if (temp.length() == charMaxNum && CharCheckUtil.isPhoneNum(phone) && login_checked.isChecked()) {
				loginBtn.setBackgroundResource(R.drawable.login_bgdown);
				loginBtn.setEnabled(true);
			} else if (temp.length() > charMaxNum) {
				s.delete(editStart - 1, editEnd);
				int tempSelection = editStart;
				codeEdit.setSelection(tempSelection);
			} else {
				loginBtn.setBackgroundResource(R.drawable.login_bg);
				loginBtn.setEnabled(false);
			}
			if (codeEdit.length() > 0) {
				clearpwd.setVisibility(View.VISIBLE);
			} else {
				clearpwd.setVisibility(View.GONE);
			}
		}
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		setIntent(intent);
	}
	
	@SuppressWarnings("rawtypes")
	@Override
	public boolean backOperate() {
		hideSoftInput(mActivity, phoneEdit);
		cleraView();
		if(hasInfo()){
			Class originClzz = mInfo.getOriginClzz();
			if(originClzz!=null && originClzz.getName().equals(IndexFragment_.class)){
				Info<Class> info = new Info<Class>(IndexFragment_.class);
				info.setOrigin(LoginActivity_.class);
				openActivity(HomeActivity_.class, info);
			}
		}
		finish();
		return true;
	}
	
	

}
